/**
 * 获取对象类型
 * @param {*} data 
 */
let getDataType = (data) => {
    let toString = Object.prototype.toString;
    let dataType = toString
        .call(data)
        .replace(/\[object\s(.+)\]/, "$1")
        .toLowerCase()
    return dataType
};

/**
 * 字符串转换为时间
 * @param  {String} src 字符串
 */
let strToDate = function (dateObj) {
    dateObj = dateObj.replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '').replace(/(-)/g, '/')
    if (dateObj.indexOf(".") > 0) dateObj = dateObj.slice(0, dateObj.indexOf("."))

    return new Date(dateObj)
}


/* 时间格式化
 * @param  {Object} dateObj 时间对象
 * @param  {String} fmt 格式化字符串
 */
let dateFormat = function (dateObj, fmt) {
    let date;
    if (getDataType(dateObj) == "string") {
        date = strToDate(dateObj)
    } else if (dateObj instanceof Date) {
        date = dateObj
    }
    else {
        date = new Date();
    }
    var o = {
        "M+": date.getMonth() + 1, //月份         
        "d+": date.getDate(), //日         
        "h+": date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, //小时         
        "H+": date.getHours(), //小时         
        "m+": date.getMinutes(), //分         
        "s+": date.getSeconds(), //秒         
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度         
        "S": date.getMilliseconds() //毫秒         
    };
    var week = {
        "0": "日",
        "1": "一",
        "2": "二",
        "3": "三",
        "4": "四",
        "5": "五",
        "6": "六"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear().toString() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + week[date.getDay().toString() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k].toString()) : (("00" + o[k].toString()).substr(("" + o[k].toString()).length)));
        }
    }
    return fmt;
}

/**
 * 获取第几周
 * @param {*} dt 
 */
let getWeek = function (dt) {
    let d1 = new Date(dt);
    let d2 = new Date(dt);
    d2.setMonth(0);
    d2.setDate(1);
    let rq = d1 - d2;
    let days = Math.ceil(rq / (24 * 60 * 60 * 1000));
    let num = Math.ceil(days / 7);
    return num;
};
/**
 * 获取昨天
 */
let getLastDay = function () {
    var date = new Date();
    date.setTime(date.getTime() - 24 * 60 * 60 * 1000);
    return dateFormat(date, "yyyy-MM-dd");
};

/**
 * dataURLtoBlob
 * @param {*} base64 
 */
let dataURLtoBlob = (base64) => {
    let arr = base64.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
        type: mime
    });
};

/**
 * dataURLtoFile
 * @param {*} base64 
 * @param {*} filename 
 */
let dataURLtoFile = (base64, filename) => {
    let arr = base64.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    let data = new File([u8arr], filename, {
        type: mime
    });
    return data;
};

/**
 * 图片压缩
 * @param {*} file 文件对象
 * @param {*} opt opt.size  opt.scale
 * @param {*} callback 
 */
let imgCompress = (file, opt) => {
    return new Promise((resolve, reject) => {
        let imgname = file.name;
        let imgtype = (imgname.substring(imgname.lastIndexOf(".") + 1)).toLowerCase();
        if (imgtype == "jpg" || imgtype == "jpeg") {
            imgtype = "image/jpeg";
        } else {
            imgtype = "image/png";
        }
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (evt) {
            let base64 = evt.target.result;
            let img = new Image();
            img.src = base64;
            img.onload = function () {
                let that = this,
                    canvas = document.createElement("canvas"),
                    ctx = canvas.getContext("2d");
                canvas.setAttribute("width", that.width);
                canvas.setAttribute("height", that.height);
                ctx.drawImage(that, 0, 0, that.width, that.height);

                // 压缩到指定体积以下（M）
                if (opt.size) {
                    let scale = 0.9;
                    (function doCompress (scale) {
                        if (base64.length / 1024 / 1024 > opt.size && scale > 0) {
                            base64 = canvas.toDataURL(imgtype, scale);
                            scale = scale - 0.1;
                            doCompress(scale);
                        } else {
                            resolve(base64);
                        }
                    })(scale);
                } else if (opt.scale) {
                    // 按比率压缩
                    base64 = canvas.toDataURL(imgtype, opt.scale);
                    resolve(base64);
                } else {
                    reject("图片压缩失败")
                }
            }
        }
    })
};

/**
 * 检测值是否为空
 * 注意: isEmpty([]) == true, isEmpty({}) == true, isEmpty([{0:false},"",0]) == true, isEmpty({0:1}) == false
 * @param {*} value 
 */
let isEmpty = function (value) {
    var isEmptyObject = function (a) {
        if (typeof a.length === "undefined") {
            var hasNonempty = Object.keys(a).some(function nonEmpty (element) {
                return !isEmpty(a[element]);
            });
            return hasNonempty ? false : isEmptyObject(Object.keys(a));
        }

        return !a.some(function nonEmpty (element) {
            return !isEmpty(element);
        });
    };
    return (
        value == false
        || typeof value === "undefined"
        || value == null
        || (typeof value === "object" && isEmptyObject(value))
    );
};

/**
 *  1微信内置浏览器 2.企业微信内置浏览器 0.其他浏览器
 */
let isWeiXin = function () {
    var ua = window.navigator.userAgent.toLowerCase();
    if ((ua.match(/MicroMessenger/i) == 'micromessenger') && (ua.match(/wxwork/i) == 'wxwork')) {
        return 2;
    } else if (ua.match(/micromessenger/i) == 'micromessenger') {
        return 1;
    } else {
        return 0;
    }
}



let getParameters = function () {
    var locUrl = window.location.search.substr(1);
    var aryParams = locUrl.split("&");
    var json = {};
    for (var i = 0; i < aryParams.length; i++) {
        var pair = aryParams[i];
        var aryEnt = pair.split("=");
        var key = aryEnt[0];
        var val = aryEnt[1];
        if (json[key]) {
            json[key] = json[key] + "," + val;
        }
        else {
            json[key] = val;
        }
        return json;
    }
}

/**
 * 根据参数名称，获取上下文中的参数。
 */
let getParameter = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
let getParameterByIndex = function (index) {
    var locUrl = window.location.hash.replace("#/");
    var aryParams = locUrl.split("/");
    if (index >= 0 && index < aryParams.length) {
        return aryParams[index];
    }
    return "";
}

/**
 * 将对象序列化成地址栏参数。
 * 
 * @param {Object} obj
 */
let serialJsonToForm = function (obj) {
    var aryForm = [];
    for (var key in obj) {
        if (obj[key]) {
            aryForm.push(key + "=" + obj[key]);
        }
    }
    if (aryForm.length == 0) return "";
    return aryForm.join("&");
}

/**
 * 将list转成map对象
 * [{id:"u1",name:name1},{id:"u2",name:name2}]
 * 转换成
 * {
 * 	u1:{id:"u1",name:name1},
 *  u2:{id:"u2",name:name2}
 * }
 * @param {Object} key
 * @param {Object} list
 */
let covertList2Map = function (key, list) {
    if (!list || list.length == 0) return {};
    var rtnObj = {};
    var aryKeys = key.split(".");
    for (var i = 0; i < list.length; i++) {
        var o = list[i];
        var tmpObj = o;
        for (var j = 0; j < aryKeys.length; j++) {
            var tmpKey = aryKeys[j];
            tmpObj = tmpObj[tmpKey];
        }
        rtnObj[tmpObj] = o;
    }
    return rtnObj;
}

/**
 *  
 * 数组中是否存在key值。
 * [1,2,3] 是否存在3
 */
let isInAry = function (ary, val) {
    for (var i = 0; i < ary.length; i++) {
        if (ary[i] == val) return true;
    }
    return false;
}

/**
 * 
 * 判断列表中指定 数据。
 * 示例：
 * [{id:"u1",name:name1},{id:"u2",name:name2}]
 * name 为id
 * val为 u1
 */
let isInList = function (ary, name, val) {
    for (var i = 0; i < ary.length; i++) {
        if (ary[i][name] == val) return true;
    }
    return false;
}

/**
 * 在数组中删除指定的值。
 * @param {Object} ary
 * @param {Object} val
 */
let removeByVal = function (ary, val) {
    for (var i = ary.length - 1; i >= 0; i--) {
        if (ary[i] != val) continue;
        ary.splice(i, 1);
    }
}

/**
 * 中文转换
 * @param {Object} n
 */
let toChineseMoney = function (n) {
    if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n))
        return "数据非法";
    var unit = "千百拾亿千百拾万千百拾元角分", str = "";
    n += "00";
    var p = n.indexOf('.');
    if (p >= 0)
        n = n.substring(0, p) + n.substr(p + 1, 2);
    unit = unit.substr(unit.length - n.length);
    for (var i = 0; i < n.length; i++)
        str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i);
    return str.replace(/零(千|百|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1").replace(/(亿)万|壹(拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整");
}

/**
 * 设置HTML
 * @param {Object} id
 * @param {Object} html
 */
let setHtml = function (id, html) {
    var reg = new RegExp("&#39;", "g");
    html = html.replace(reg, "'");
    reg = new RegExp("&amp;", "g");
    html = html.replace(reg, "&");
    var container = document.getElementById(id);
    container.innerHTML = html //.replace(html.substring(html.indexOf("<script>"),html.indexOf("</script>") + 9),"");
    var aryScripts = container.getElementsByTagName('script');
    if (!aryScripts || aryScripts.length == 0) return;
    for (var i = 0; i < aryScripts.length; i++) {
        var oldScript = aryScripts[i];
        container.removeChild(oldScript);
        var src = oldScript.getAttribute("src");
        var newScript = document.createElement('script');
        newScript.type = 'text/javascript';
        if (src) {
            newScript.setAttribute("src", src);
        }
        else {
            newScript.innerHTML = oldScript.innerHTML;
        }
        container.appendChild(newScript);
    }
}

/**
 * 插入脚本
 * id：容器ID
 * aryScript:脚本对象。
 *[
 *	{type:"src",content:"脚本地址"},
 *	{type:"script",content:"脚本内容"}
 *]
 */
let insertScript = function (id, aryScript) {
    if (!aryScript) return;
    var container = document.getElementById(id);

    for (var i = 0; i < aryScript.length; i++) {
        var obj = aryScript[i];
        var newScript = document.createElement('script');
        newScript.type = 'text/javascript';
        if (obj.type == "src") {
            newScript.setAttribute("src", obj.content);
        }
        else {
            newScript.innerHTML = obj.content;
        }
        container.appendChild(newScript);
    }
}


/**
 * 解析html 将html和脚本进行分离。
 * 返回数据格式为:
 *	{html:"html内容",
 * 		script:[
 * 			{type:"src",content:"脚本地址"},
 * 			{type:"script",content:"脚本内容"}
 * 		]
 *	}
 * @param {Object} html
 */
let parseHtml = function (html) {
    var regSrc = /<script\s*?src=('|")(.*?)\1\s*>(.|\n|\r)*?<\/script>/img;
    var match = regSrc.exec(html);
    var aryToReplace = [];
    var rtn = [];
    while (match != null) {
        aryToReplace.push(match[0]);
        var o = { type: "src", content: match[2] };
        rtn.push(o);
        match = regSrc.exec(html);
    }
    //替换脚本
    for (var i = 0; i < aryToReplace.length; i++) {
        html = html.replace(aryToReplace[i], "");
    }
    aryToReplace = [];
    var regScript = /<script(?:\s+[^>]*)?>((.|\n|\r)*?)<\/script>/img;

    match = regScript.exec(html);

    while (match != null) {
        aryToReplace.push(match[0]);
        o = { type: "script", content: match[1] };
        rtn.push(o);
        match = regScript.exec(html);
    }
    //替换脚本
    for (i = 0; i < aryToReplace.length; i++) {
        html = html.replace(aryToReplace[i], "");
    }
    return { html: html, script: rtn };
}

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

/**
 * 日期相减。
 * 参数1： date 
 * 参数2：减的日期格式。
 * @param {Object} date
 * @param {Object} format
 */
Date.prototype.subtract = function (date, format) {
    var minute = (this.getTime() - date.getTime()) / (60 * 1000);
    var day = parseInt(minute / (24 * 60));
    var hour = parseInt(minute / 60);
    var rtn = 0;
    switch (format) {
        //分钟
        case 1:
            rtn = minute;
            break;
        //小时
        case 2:
            rtn = hour;
            break;
        //天数
        default:
            rtn = day + 1;
    }
    return rtn;
}

String.prototype.replaceAll = function (toReplace, replaceWith) {
    var reg = new RegExp(toReplace, "igm");
    var rtn = this.replace(reg, replaceWith);
    return rtn;
}

String.prototype.startWith = function (str) {
    var reg = new RegExp("^" + str);
    return reg.test(this);
}

String.prototype.endWith = function (str) {
    var reg = new RegExp(str + "$");
    return reg.test(this);
}

String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

/**
 * 将字符串解析为日期。 
 */
String.prototype.parseDate = function () {
    //yyyy-MM-dd
    var year = 1970;
    //yyyy-MM-dd
    var aryDateTime = this.split(" ");

    var date = aryDateTime[0];
    var aryTmp = date.split("-");
    year = parseInt(aryTmp[0]);
    var mon = parseInt(aryTmp[1]) - 1;
    var day = parseInt(aryTmp[2]);
    var hour = 0;
    var minute = 0;
    if (aryDateTime.length == 2) {
        var time = aryDateTime[1];
        aryTmp = time.split(":");
        hour = parseInt(aryTmp[0]);
        minute = parseInt(aryTmp[1]);
    }
    return new Date(year, mon, day, hour, minute);


}

Array.prototype.contains = function (obj) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == obj) {
            return true;
        }
    }
    return false;
}

/**
 * 获取count位随机数
 * @param {Object} count 位数
 */
let getRandomNum = function (count) {
    var Num = "";
    for (var i = 0; i < count; i++) {
        Num += Math.floor(Math.random() * 10);
    }
    return Num;
}

/**
 * 计算控件权限。
 */
let calcRight = function (vm) {
    var readonly = false;
    var read = vm.readonly;
    if (typeof (read) == "string") {
        readonly = read == "true" ? true : false;
    }
    else {
        readonly = vm.readonly;
    }
    if (readonly) return "r";
    var tmp = vm.permissionkey;
    if (!tmp) return readonly ? "r" : "w";
    if (!vm.permission) return "w";

    if (!vm.permission[tmp]) {
        return readonly ? "r" : "w";
    }
    if (vm.permission[tmp].right != 'w') {
        return 'r';
    }
    return vm.permission[tmp].right;
}

/**
 * 将formmodels转换成 提交的JSON结构。
 */
let convertBoJson = function (formModels) {
    var jsonData = {};
    var aryJson = [];
    for (var i = 0; i < formModels.length; i++) {
        var formModel = formModels[i];
        var formData = {};
        formData.boDefId = formModel.boDefId;
        formData.data = formModel.jsonData;
        aryJson.push(formData);
    }
    jsonData.bos = aryJson;
    return jsonData;
}

let htmlFilter = function (text) {
    var reg = /<[^<>]+>/g;//1、全局匹配g肯定忘记写,2、<>标签中不能包含标签实现过滤HTML标签
    text = text.replace(reg, '');//替换HTML标签
    text = text.replace(/&nbsp;/ig, '');//替换HTML空格
    return text;
};

let stripscript = function (str) {
    var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]");
    return pattern.test(str);
}

export {
    getDataType,
    dateFormat,
    dataURLtoBlob,
    dataURLtoFile,
    imgCompress,
    isEmpty,
    getWeek,
    getLastDay,
    isWeiXin,
    getParameters,
    getParameter,
    getParameterByIndex,
    serialJsonToForm,
    covertList2Map,
    isInAry,
    isInList,
    removeByVal,
    toChineseMoney,
    setHtml,
    insertScript,
    parseHtml,
    getRandomNum,
    calcRight,
    convertBoJson,
    htmlFilter,
    stripscript
}